package com.zgw.his.design.resource;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

import com.zgw.his.common.ValueUtil;
import com.zgw.his.design.common.LocalResourceHelp;
import com.zgw.his.design.model.Folder;
import com.zgw.his.design.model.MedicalResource;
import com.zgw.his.design.model.Template;
import com.zgw.his.server.emr.entity.Temrtemplate;
import com.zgw.his.server.emr.entity.Temrtemplatesort;

@SuppressWarnings("restriction")
public class LocalResoureceManager {
	// 资源根路径 RESOURCE ROOT PATH
	public final static String RRP = "/templates/src";

	// 默认母版路径 DEFAULT TEMPLATE PATH
	private final static String DTP = "/templates/DEFAULT.xwt";

	private Map<String, Folder> folders = new HashMap<String, Folder>();
	private Map<String, Template> templates = new HashMap<String, Template>();
	private List<Folder> rootFolders = new ArrayList<Folder>(); // 根目录
	private Folder defaultFolder; // 缺省目录

	public LocalResoureceManager() {
		defaultFolder = new Folder(null, "DEFAULT");
		defaultFolder.setPath(RRP);
		defaultFolder.setNumber("DEFAULT");
		defaultFolder.setState(Folder.STATE_NOMAL);
	}

	/**
	 * 持久化 属性
	 * 
	 * @throws CoreException
	 * */
	public void persistent(MedicalResource resource) throws CoreException {
		if (resource instanceof Template) {
			Template temp = (Template) resource;
			temp.setPersistentProperty(MedicalResource.KEY_NUMBER,
					temp.getNumber());
			temp.setPersistentProperty(MedicalResource.KEY_STATE,
					temp.getState() + "");
			temp.setPersistentProperty(MedicalResource.KEY_VERSION,
					temp.getVersion() + "");
		} else if (resource instanceof Folder) {
			Folder f = (Folder) resource;
			f.setPersistentProperty(MedicalResource.KEY_NUMBER, f.getNumber());
			f.setPersistentProperty(MedicalResource.KEY_STATE, f.getState()
					+ "");
		}
	}

	/**
	 * 重命名 资源 名称
	 * 
	 * @throws Exception
	 * */
	public void rename(MedicalResource mr, String newName) throws Exception {
		String path = mr.getResource().getFullPath().toString();
		String newPath = path.substring(0, path.lastIndexOf("/")) + "/"
				+ newName + ".xwt";
		LocalResourceHelp.move(path, newPath);

		if (mr instanceof Template) {
			((Template) mr).setPath(newPath);
			((Template) mr).setName(newName);
		} else if (mr instanceof Folder) {
			((Folder) mr).setPath(newPath);
			((Folder) mr).setName(newName);
		}
		persistent(mr);
	}

	/**
	 * @throws CoreException
	 * 
	 * */
	public void modifyNumber(MedicalResource resource, String newNumber)
			throws CoreException {
		if (resource instanceof Template) {
			this.templates.remove(((Template) resource).getNumber());
			((Template) resource).setNumber(newNumber);
			templates.put(newNumber, (Template) resource);
		} else if (resource instanceof Folder) {
			this.folders.remove(((Folder) resource).getNumber());
			((Folder) resource).setNumber(newNumber);
			this.folders.put(newNumber, (Folder) resource);
		}
		persistent(resource);
	}

	/**
	 * 加载本地模板资源 <B>包括目录和模版</B>
	 * 
	 * @return 本地模版根目录
	 * @throws CoreException
	 * */
	public Folder[] loadLocal() throws CoreException {
		rootFolders.clear();
		folders.clear();
		templates.clear();
		defaultFolder.getTemplates().clear();

		IFolder rootFolder = LocalResourceHelp.getFolder(RRP);
		for (IResource r : rootFolder.members()) {
			if (r instanceof IFolder) {
				convertFolder(null, (IFolder) r);
			} else if (r instanceof IFile && isXwt((IFile) r)) {
				convertTemplate(null, (IFile) r);
			}
		}
		folders.put(defaultFolder.getNumber(), defaultFolder);
		rootFolders.add(defaultFolder);
		Folder[] folders = new Folder[rootFolders.size()];

		return rootFolders.toArray(folders);
	}

	private Folder convertFolder(Folder parent, IFolder f) throws CoreException {
		Folder folder = new Folder(parent, f.getName());
		folder.setPath(f.getFullPath().toString());

		String number = folder.getPersistentProperty(Folder.KEY_NUMBER);
		number = number == null ? defaultNumber() : number;
		folder.setNumber(number);
		String stateTxt = folder.getPersistentProperty(Folder.KEY_STATE);
		int state = stateTxt == null ? MedicalResource.STATE_NEW : Integer
				.parseInt(stateTxt);
		folder.setState(state);
		persistent(folder);
		folders.put(folder.getNumber(), folder);
		if (parent == null) {
			rootFolders.add(folder);
		}
		// 构建子节点
		for (IResource r : f.members()) {
			if (r instanceof IFolder) {
				convertFolder(folder, (IFolder) r);
			} else if (r instanceof IFile && isXwt((IFile) r)) {
				convertTemplate(folder, (IFile) r);
			}
		}
		return folder;
	}

	private Template convertTemplate(Folder parent, IFile f)
			throws CoreException {
		parent = parent == null ? defaultFolder : parent;
		Template t = new Template(parent, removeSuffix(f.getName()));
		t.setPath(f.getFullPath().toString());

		String version = t.getPersistentProperty(t.KEY_VERSION);
		String number = t.getPersistentProperty(t.KEY_NUMBER);
		String s = t.getPersistentProperty(t.KEY_STATE);

		int state = s == null ? MedicalResource.STATE_NEW : Integer.parseInt(s);
		number = number == null ? defaultNumber() : number; // 默认编号
		t.setNumber(number);
		t.setVersion(version);
		t.setState(state);
		persistent(t);
		templates.put(t.getNumber(), t);
		return t;
	}

	/**
	 * 创建一个 Folder对象
	 * 
	 * @throws Exception
	 * */
	public Folder createFolder(Folder parent, String name, String number)
			throws Exception {
		Folder folder = null;
		String path;
		if (parent == null) {
			for (Folder f : getRootFolders()) {
				if (f.getName().equals(name)) {
					folder = f;
					break;
				}
			}
			path = RRP + "/" + name;
		} else {
			for (Folder f : parent.getChidren()) {
				if (f.getName().equals(name)) {
					folder = f;
					break;
				}
			}
			path = parent.getPath() + "/" + name;
		}
		if (folder == null) {
			IFolder f = LocalResourceHelp.createIFolder(path);
			folder = convertFolder(parent, f);
		}
		if (ValueUtil.hasValue(number)) {
			modifyNumber(folder, number);
		}
		return folder;
	}

	public Folder createFolder(Folder parent, String name) throws Exception {
		return createFolder(parent, name, null);
	}

	/**
	 * 删除一个 Folder对象
	 * 
	 * @throws CoreException
	 * */
	public void deleteFolder(Folder f) throws CoreException {
		LocalResourceHelp.deleteResource(f.getResource());
		for (Folder fo : f.getChidren()) { // 删除其下子目录
			deleteFolder(fo);
		}
		for (Template t : f.getTemplates()) {
			deleteTemplate(t);
		}
		if (folders.containsKey(f.getNumber())) {
			folders.remove(f.getNumber());
		}
		if (f.getParent() != null) {
			f.getParent().remove(f);
		}
	}

	/**
	 * 创建一个 Template 对象
	 * 
	 * @param parent
	 *            模版 父节点
	 * @param name
	 *            模版名称
	 * @param number
	 *            模版指定编号
	 * @param content
	 *            模版默认填充的内容
	 * */
	public Template createTemplate(Folder parent, String name, String number,
			String content) throws Exception {
		String path;
		Template template = null;
		if (parent == null) {
			for (Template t : defaultFolder.getTemplates()) {
				if (t.getName().equals(name)) {
					template = t;
					break;
				}
			}
			path = RRP + "/" + name + ".xwt";
		} else {
			for (Template t : parent.getTemplates()) {
				if (t.getName().equals(name)) {
					template = t;
					break;
				}
			}
			path = parent.getPath() + "/" + name + ".xwt";
		}

		if (template == null) {
			IFile f = LocalResourceHelp.createIFile(path, content);
			template = convertTemplate(parent, f);
		}
		if (ValueUtil.hasValue(number)) {// 指定新的编号
			modifyNumber(template, number);
		}
		return template;
	}

	/**
	 * 删除一个Template 对象
	 * 
	 * @throws CoreException
	 * */
	public void deleteTemplate(Template t) throws CoreException {
		LocalResourceHelp.deleteResource(t.getResource());
		if (templates.containsKey(t.getNumber())) {
			templates.remove(t.getNumber());
		}
		if (t.getFolder() != null) {
			t.getFolder().remove(t);
		}
	}

	public Folder getFolder(String number) {
		return folders.get(number);
	}

	/**
	 * 获得所有 Folder
	 * */
	public Folder[] getFolders() {
		return folders.values().toArray(new Folder[folders.size()]);
	}

	public Template getTemplate(String number) {
		return templates.get(number);
	}

	/**
	 * 获得所有 Template
	 * */
	public Template[] getTemplates() {
		return templates.values().toArray(new Template[templates.size()]);
	}

	public Folder[] getRootFolders() {
		Folder[] folders = new Folder[rootFolders.size()];
		return rootFolders.toArray(folders);
	}

	// ======================================================
	// 工具方法
	// ======================================================
	private boolean isXwt(IFile file) {
		return file != null && file.getFullPath().toString().endsWith(".xwt");
	}

	private String removeSuffix(String fileName) {
		if (fileName.lastIndexOf(".xwt") > 0) {
			return fileName.substring(0, fileName.lastIndexOf(".xwt"));
		}
		return fileName;
	}

	private static int defaultNumberCount = 1;

	private static String defaultNumber() {
		SimpleDateFormat s = new SimpleDateFormat("yyMMddhhmmss");
		return s.format(new Date()) + (defaultNumberCount++);
	}

	/**
	 * 是否为缺省目录
	 * */
	public boolean isDefaultFolder(Folder folder) {
		return folder == defaultFolder;
	}

}
